package com.twang.stock.design.impl;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.design.IndexDataTask;
import com.twang.stock.dto.IndexedInfo;
import com.twang.stock.entity.DfcfZhangDie;
import com.twang.stock.mapper.TodayQinXuMapper;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.task.QueryBanKuaiAndDaPan;
import com.twang.stock.task.QueryZhangDieTingTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 获取大盘数据
 */
@Slf4j
@Service
public class DfcfZhangDieModel   extends IndexedInfo implements IndexDataTask {

    public static String cache_key = "DfcfZhangDieModel";

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private TodayQinXuMapper todayQinXuMapper;
    @Override
    public void execute(ModelAndView modelAndView, CountDownLatch latch) throws Exception {
        // 执行任务的逻辑，例如获取沪深指数
        try {
            List<DfcfZhangDie> dfcfZhangDies;
            //查询
            Object obj = redisUtil.get(cache_key);
            if (null == obj ) {
                dfcfZhangDies = QueryBanKuaiAndDaPan.getDfcfZhangDie();
            } else {
                dfcfZhangDies = JSONObject.parseArray(obj.toString(), DfcfZhangDie.class);
            }
            dfcfZhangDies.forEach(item -> {
                if ("000001".equals(item.getTypeCode())) {
                    modelAndView.addObject("sh", item);
                } else {
                    modelAndView.addObject("sz", item);
                }
            });
            BigDecimal totalAmount= todayQinXuMapper.getLastTotalAMount();
            modelAndView.addObject("AtotalAmount", totalAmount.divide(new BigDecimal(100000000)).setScale(2, BigDecimal.ROUND_HALF_UP));
            redisUtil.set(QueryZhangDieTingTask.AMOUNT_CACTH_KEY,totalAmount);
            log.info("沪深 = {}", JSONObject.toJSONString(dfcfZhangDies));
            //
            setDaceChangDie(JSONObject.toJSONString(dfcfZhangDies));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            log.info("大盘数据 执行完成，当前剩余条数:{}", latch.getCount());
            latch.countDown();
        }
    }
}

